package com.aiboleepro.handler;

import com.aiboleepro.base.BaseException;
import com.aiboleepro.base.BaseMessage;
import com.aiboleepro.constant.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理器
 *
 * @author aiboleepro
 * @date 2018-05-10 下午2:54
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = Exception.class)
    public BaseMessage<String> handler(Exception exception, HttpServletRequest request) {
        String requestURI = "";
        if (null != request) {
            requestURI = request.getRequestURI();
        }
        BaseException baseException;
        if (exception instanceof BaseException) {
            baseException = (BaseException) exception;
            log.error("[{}] request catch custom error code:{} desc:{}", requestURI, baseException.getCode(), baseException.getDesc());
        } else {
            baseException = new BaseException(ErrorCode.SYSTEM_ERROR, exception.getMessage());
            log.error("[{}] request catch system error {}", requestURI, exception.getMessage());
        }
        return new BaseMessage<>(baseException.getCode(), baseException.getDesc(), null);
    }
}
